#coding=utf-8
#使用zipfile做目录压缩，解压缩功能
#code by foRK
#2013/10/05,w4n9@sina.com

import os,os.path
import zipfile
import sys

if len(sys.argv) < 2:
	print 'version 0.1'
	print '%s -zip [G:/python/] [G:/python.zip]' % sys.argv[0]
	print '%s -uzip [G:/python.zip] [G:/python/]' % sys.argv[0]
	sys.exit(1)
	
PARA = sys.argv[1]
PATH1 = sys.argv[2]
PATH2 = sys.argv[3]

def zip_dir(dirname,zipfilename):
    filelist = []
    if os.path.isfile(dirname):
        filelist.append(dirname)
    else :
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))
        
    zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
    for tar in filelist:
        arcname = tar[len(dirname):]
        #print arcname
        zf.write(tar,arcname)
    zf.close()


def unzip_file(zipfilename, unziptodir):
    if not os.path.exists(unziptodir): os.mkdir(unziptodir, 0777)
    zfobj = zipfile.ZipFile(zipfilename)
    for name in zfobj.namelist():
        name = name.replace('\\','/')
       
        if name.endswith('/'):
            os.mkdir(os.path.join(unziptodir, name))
        else:            
            ext_filename = os.path.join(unziptodir, name)
            ext_dir= os.path.dirname(ext_filename)
            if not os.path.exists(ext_dir) : os.mkdir(ext_dir,0777)
            outfile = open(ext_filename, 'wb')
            outfile.write(zfobj.read(name))
            outfile.close()

if __name__ == '__main__':
	if PARA == '-zip':
		zip_dir(PATH1,PATH2)
	elif PARA == '-uzip':
		unzip_file(PATH2,PATH1)
#    zip_dir(r'G:/python/',r'G:/python.zip')
#    unzip_file(r'E:/python/learning/zip.zip',r'E:/python/learning2')